package com.ksyun.ks3.services.handler;

import android.util.Log;

import com.ksyun.ks3.exception.Ks3ClientException;
import com.ksyun.ks3.exception.Ks3ServiceException;
import com.ksyun.ks3.services.request.Ks3HttpRequest;
import com.ksyun.ks3.util.Constants;
import com.ksyun.ks3.util.IOUtils;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Response;

public abstract class AsyncHttpResponseHandler implements Callback {
    Ks3HttpRequest request;

    @Override
    public void onFailure(Call call, IOException e) {
        if (!call.isCanceled()) {
            call.cancel();
        }
        onFailure(request, new Ks3ClientException(e), null);
        e.printStackTrace();
        Log.e(Constants.LOG_TAG, e.toString());
    }

    @Override
    public void onResponse(Call call, Response response) {
        Headers headers = response.headers();
        int code = response.code();
        InputStream responseBody;
        try {
            responseBody = response.body().byteStream();
            byte[] responseBytes = IOUtils.toByteArray(responseBody);
            if (code < 300 & code >= 200) {
                onSuccess(request, code, headers, responseBytes);
            } else {
                Ks3ServiceException serviceException = new Ks3ServiceException(code, headers, responseBytes);
                onFailure(request, null, serviceException);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(Constants.LOG_TAG, e.toString());
            // @TODO 处理cancel导致的异常 权宜之计 后续有好的处理方式后再做更新
            if (call.isExecuted() && call.isCanceled()) {
                onCancel();
            } else {
                onFailure(request, new Ks3ClientException(e), null);
            }
        }
    }

    public abstract void onSuccess(Ks3HttpRequest request, int statusCode, Headers responseHeaders, byte[] response);

    public abstract void onFailure(Ks3HttpRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException);

    public abstract void onRetry(int retryNo);

    public void onCancel() {
    }

    ;

    public void onProgress(long bytesWritten, long totalSize) {
    }

    public Ks3HttpRequest getRequest() {
        return request;
    }

    public void setRequest(Ks3HttpRequest request) {
        this.request = request;
    }
}
